package com.example.shop.controller;

import com.example.shop.entity.Products;
import com.example.shop.model.ApiResponse;
import com.example.shop.service.ProductsService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * author: adnaan
 * create: 2023-11-07 14:58
 * Description:
 */
@RestController
@RequestMapping("/products")
public class ProductsController {

    @Autowired
    private ProductsService productsService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping("/page")
    public ApiResponse page(@RequestParam Integer currentPage,
                            @RequestParam Integer pageSize,
                            @RequestParam String productName){
        return productsService.page(currentPage,pageSize,productName);
    }

    @PostMapping("/addProduct")
    public ApiResponse addProduct(@RequestBody Products products){
        return productsService.addProduct(products);
    }

    @PutMapping("/saveProduct")
    public ApiResponse saveProduct(@RequestBody Products products){
        return productsService.saveProduct(products);
    }

    @DeleteMapping("/delProduct")
    public ApiResponse delProduct(@RequestParam String productId){
        return productsService.delProduct(productId);
    }

    @GetMapping("/productDetail")
    public ApiResponse productDetail(String key) throws JsonProcessingException {
        HashOperations hashOperations = stringRedisTemplate.opsForHash();
        Object v = hashOperations.entries(key);
        // redis中没有数据, 从mongoDb中获取
        if (((Map<?, ?>) v).isEmpty()) {
            Products pro = productsService.findDetail(key);
            ObjectMapper mapper = new ObjectMapper();
            v = mapper.writeValueAsString(pro);

            // v 不为空的情况下，写入redis
            if (pro != null) {
                hashOperations.put(key, "name", pro.getName());
                hashOperations.put(key, "id", pro.getId());
                hashOperations.put(key, "price", Double.toString(pro.getPrice()));
                hashOperations.put(key, "image", String.format(pro.getImage()));
                hashOperations.put(key, "description", String.format(pro.getDescription()));
            } else {
                return null;
            }
            return ApiResponse.success("200","获取成功",pro);
        } else {
            return ApiResponse.success("200","获取成功",v);
        }
    }
}
